import { useMemo, useEffect, useState } from "react";
import TenantBusiness from "@/business/TenantBussiness";
import leaseStore from "@/stores/LeaseStore";
import { HouseConstant } from "@/constant/HouseConstant";
import houseStore from "@/stores/HouseStore";
import { HouseEntity } from "@/entities/HouseEntity";
import { CommonUtil } from "@/utils/CommonUtil";

const useHook = () => {
  const { landlordHouseList } = houseStore;
  const { currentRentBillTenant } = leaseStore;
  const { tenantId, leaseDate } = currentRentBillTenant;
  const { FieldToNameMap, FieldToUnit } = HouseConstant;

  // 当前被收租的租客信息
  const [currentTenant, setCurrentTenant] = useState({} as any);

  // 正在收租的房屋信息
  const [currentHouse, setCurrentHouse] = useState<HouseEntity.IBaseHouse>(
    {} as HouseEntity.IBaseHouse
  );

  useEffect(() => {
    (async function () {
      const [tenant] = (await TenantBusiness.getTenantByIdList(
        `${tenantId}`
      )) as any;
      setCurrentTenant(tenant);
    })();
  }, [tenantId]);

  /**
   * 展示的基础信息
   */
  const fillBillItems = useMemo(() => {
    const { identityName } = currentTenant;
    const { houseAddress, houseId } = currentRentBillTenant;
    const currentHouse =
      landlordHouseList?.find((h) => h.houseId === houseId) || {};
    setCurrentHouse(currentHouse);
    const { waterFee, electricityFee, price, internetFee, fuelFee } =
      currentHouse;
    const fillBillArr = [
      {
        text: "姓名：",
        content: identityName,
      },
      {
        text: "房屋地址：",
        content: houseAddress,
      },
      {
        text: `${FieldToNameMap.price}：`,
        content: `${price}${FieldToUnit.price}`,
      },
      {
        text: `${FieldToNameMap.waterFee}：`,
        content: `${waterFee}${FieldToUnit.waterFee}`,
      },
      {
        text: `${FieldToNameMap.electricityFee}：`,
        content: `${electricityFee}${FieldToUnit.electricityFee}`,
      },
    ];
    if (internetFee > 0) {
      fillBillArr.push({
        text: `${FieldToNameMap.internetFee}：`,
        content: `${internetFee}${FieldToUnit.internetFee}`,
      });
    }
    if (fuelFee > 0) {
      fillBillArr.push({
        text: `${FieldToNameMap.fuelFee}：`,
        content: `${fuelFee}${FieldToUnit.fuelFee}`,
      });
    }
    fillBillArr.push({
      text: "入住时间",
      content: `${CommonUtil.formatUtcTime(leaseDate)?.slice(0, 10)}`,
    });
    return fillBillArr;
  }, [currentTenant, currentRentBillTenant, landlordHouseList]);

  return {
    fillBillItems,
    currentHouse,
  };
};

export default useHook;
